/**
 * 权限验证中间件
 */

const jwt = require('jsonwebtoken');
const secret = 'liyu'; // 应该从环境变量获取

// 用户角色枚举
const USER_ROLES = {
  ADMIN: 'admin',
  USER: 'user'
};

/**
 * 验证JWT Token
 */
const verifyToken = (req, res, next) => {
  let token = req.headers.authorization || req.headers.token;

  if (!token) {
    return res.status(401).json({
      code: 401,
      message: '缺少访问令牌'
    });
  }

  // 如果token以"Bearer "开头，提取实际的token值
  if (token.startsWith('Bearer ')) {
    token = token.slice(7); // 移除"Bearer "前缀
  }

  try {
    const decoded = jwt.verify(token, secret);
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(403).json({
      code: 403,
      message: '令牌无效或已过期'
    });
  }
};

/**
 * 验证管理员权限
 */
const requireAdmin = (req, res, next) => {
  // 首先验证token
  verifyToken(req, res, (err) => {
    if (err) return;
    
    // 从数据库获取用户信息验证角色
    const db = require('../utils/db');
    const username = req.user.username;
    
    const sql = `SELECT role FROM user WHERE username = ?`;
    db.query(sql, [username], (error, results) => {
      if (error) {
        return res.status(500).json({
          code: 500,
          message: '服务器错误'
        });
      }
      
      if (results.length === 0) {
        return res.status(404).json({
          code: 404,
          message: '用户不存在'
        });
      }
      
      const userRole = results[0].role;
      if (userRole !== USER_ROLES.ADMIN) {
        return res.status(403).json({
          code: 403,
          message: '权限不足，需要管理员权限'
        });
      }
      
      req.userRole = userRole;
      next();
    });
  });
};

/**
 * 验证用户权限（管理员或资源所有者）
 */
const requireOwnerOrAdmin = (req, res, next) => {
  verifyToken(req, res, (err) => {
    if (err) return;
    
    const db = require('../utils/db');
    const username = req.user.username;
    
    const sql = `SELECT user_id, role FROM user WHERE username = ?`;
    db.query(sql, [username], (error, results) => {
      if (error) {
        return res.status(500).json({
          code: 500,
          message: '服务器错误'
        });
      }
      
      if (results.length === 0) {
        return res.status(404).json({
          code: 404,
          message: '用户不存在'
        });
      }
      
      const user = results[0];
      req.currentUser = user;
      
      // 管理员可以访问所有资源
      if (user.role === USER_ROLES.ADMIN) {
        req.userRole = user.role;
        return next();
      }
      
      // 普通用户只能访问自己的资源
      const resourceUserId = req.params.userId || req.body.user_id || req.query.user_id;
      if (resourceUserId && parseInt(resourceUserId) !== user.user_id) {
        return res.status(403).json({
          code: 403,
          message: '权限不足，只能访问自己的资源'
        });
      }
      
      req.userRole = user.role;
      next();
    });
  });
};

/**
 * 可选的权限验证（不强制要求登录）
 */
const optionalAuth = (req, res, next) => {
  let token = req.headers.authorization || req.headers.token;

  if (!token) {
    req.user = null;
    req.userRole = null;
    return next();
  }

  // 如果token以"Bearer "开头，提取实际的token值
  if (token.startsWith('Bearer ')) {
    token = token.slice(7); // 移除"Bearer "前缀
  }

  try {
    const decoded = jwt.verify(token, secret);

    // 获取用户完整信息
    const db = require('../utils/db');
    const sql = `SELECT user_id, username, role FROM user WHERE username = ?`;
    db.query(sql, [decoded.username], (error, results) => {
      if (error || results.length === 0) {
        req.user = null;
        req.userRole = null;
      } else {
        req.user = decoded;
        req.currentUser = results[0];
        req.userRole = results[0].role;
      }
      next();
    });
  } catch (error) {
    req.user = null;
    req.userRole = null;
    next();
  }
};

/**
 * 权限检查工具函数
 */
const hasPermission = (userRole, requiredPermission) => {
  const permissions = {
    [USER_ROLES.ADMIN]: [
      'user:view', 'user:create', 'user:edit', 'user:delete',
      'restaurant:view', 'restaurant:create', 'restaurant:edit', 'restaurant:delete',
      'dish:view', 'dish:create', 'dish:edit', 'dish:delete',
      'order:view', 'order:view:all', 'order:edit', 'order:delete',
      'system:settings', 'system:logs'
    ],
    [USER_ROLES.USER]: [
      'restaurant:view', 'dish:view', 'order:view'
    ]
  };
  
  const userPermissions = permissions[userRole] || [];
  return userPermissions.includes(requiredPermission);
};

/**
 * 创建权限验证中间件
 */
const requirePermission = (permission) => {
  return (req, res, next) => {
    verifyToken(req, res, (err) => {
      if (err) return;
      
      const db = require('../utils/db');
      const username = req.user.username;
      
      const sql = `SELECT role FROM user WHERE username = ?`;
      db.query(sql, [username], (error, results) => {
        if (error) {
          return res.status(500).json({
            code: 500,
            message: '服务器错误'
          });
        }
        
        if (results.length === 0) {
          return res.status(404).json({
            code: 404,
            message: '用户不存在'
          });
        }
        
        const userRole = results[0].role;
        if (!hasPermission(userRole, permission)) {
          return res.status(403).json({
            code: 403,
            message: '权限不足'
          });
        }
        
        req.userRole = userRole;
        next();
      });
    });
  };
};

module.exports = {
  verifyToken,
  requireAdmin,
  requireOwnerOrAdmin,
  optionalAuth,
  requirePermission,
  hasPermission,
  USER_ROLES
};
